<?php


namespace app\home\services;

use app\admin\model\QuanGuanMemberModel;

class MemberService
{
    private $model;

    public function __construct()
    {
        $this->model = new QuanGuanMemberModel();
    }

    /**
     * 新增或修改
     * @param $id
     * @param $data
     */
    public function save($id, $data)
    {
        if ($id) {
            $info = $this->getMemberInfoByMobile($data['mobile']);
            if (!empty($info)) {
                if ($info['id'] != $id) {
                    return [-1, '该手机号已注册'];
                }
            }
            $res = $this->model->save($data, ['id' => $id]);
            if ($res) {
                return [0, '修改成功', $id];
            } else {
                return [-1, '修改失败', $id];
            }
        } else {
            $info = $this->getMemberInfoByMobile($data['mobile']);
            if (!empty($info)) {
                return [-1, '该手机号已注册'];
            }
            $data['create_time'] = time();
            $res = $this->model->save($data);
            if ($res) {
                return [0, '新增成功', $this->model->id];
            } else {
                return [-1, '新增失败', 0];
            }
        }
    }

    public function getMemberInfoByMobile($mobile)
    {
        if ($mobile == "") {
            return [];
        }
        $info = $this->model->where([
            'mobile' => $mobile
        ])->find();
        return $info;
    }

    public function getMemberInfoByToken($token, $field = [])
    {
        if ($token == "") {
            return [];
        }
        $info = $this->model->where([
            'token' => $token
        ])->field($field)->find();
        return $info;
    }

    public function getMemberInfoById($id, $field = [])
    {
        if ($id <= 0) {
            return [];
        }
        $info = $this->model->where([
            'id' => $id
        ])->field($field)->find();
        return $info;
    }

    public function getCoachListByStoreId($storeId, $field = [])
    {
        $list = $this->model->where([
            'store_id' => $storeId
        ])->where([
            'status' => 1,
            'is_delete' => 1,
            'identity' => 3,
        ])->field($field)->select();
        return $list;
    }
}